package com.brillilab.service.logic.kit;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.brillilab.domain.vo.user.UserInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.brillilab.common.alioss.OssFileEnum;
import com.brillilab.common.constant.ResultEnum;
import com.brillilab.common.entity.PageVo;
import com.brillilab.common.utils.MyBeanUtils;
import com.brillilab.domain.enums.common.BoolEnum;
import com.brillilab.domain.enums.kit.KitEnum;
import com.brillilab.domain.enums.kit.KitEnum.Classify;
import com.brillilab.domain.pa.kit.SampleAddMorePa;
import com.brillilab.domain.pa.kit.SampleAddPa;
import com.brillilab.domain.pa.kit.SampleAttrPa;
import com.brillilab.domain.pa.kit.SampleModifyPa;
import com.brillilab.domain.pa.kit.SampleSearchPa;
import com.brillilab.domain.po.inventory.ReagentInventory;
import com.brillilab.domain.po.kit.Kit;
import com.brillilab.domain.po.kit.KitSpec;
import com.brillilab.domain.po.kit.Reagent;
import com.brillilab.domain.po.kit.SampleAttr;
import com.brillilab.domain.po.kit.SampleTemplate;
import com.brillilab.domain.po.system.FileManage;
import com.brillilab.domain.vo.kit.SampleInfoVo;
import com.brillilab.domain.vo.kit.SampleListVo;
import com.brillilab.domain.vo.kit.SampleSpecVo;
import com.brillilab.domain.vo.kit.SampleTemplateGroupVo;
import com.brillilab.service.constant.ServiceConstant;
import com.brillilab.service.core.elsearch.IEsKitSaveService;
import com.brillilab.service.core.inventory.IReagentInventoryService;
import com.brillilab.service.core.kit.IKitService;
import com.brillilab.service.core.kit.IKitSpecService;
import com.brillilab.service.core.kit.IReagentService;
import com.brillilab.service.core.kit.ISampleAttrService;
import com.brillilab.service.core.kit.ISampleTemplateService;
import com.brillilab.service.core.system.IDictService;
import com.brillilab.service.core.system.IFileManageService;

/**
 * 样品Logic
 * @author lj
 *
 */
@Service
@Transactional
public class SampleLogic {
	@Autowired
	private IKitService kitService;
	@Autowired
	private IKitSpecService kitSpecService;
	@Autowired
	private IReagentService reagentService;
	@Autowired
	private ISampleAttrService sampleAttrService;
	@Autowired
	private IDictService dictService;
	@Autowired
	private ISampleTemplateService sampleTemplateService;
	@Autowired
	private IEsKitSaveService esKitSaveService;
	@Autowired
	private IFileManageService fileManageService;
	@Autowired
	private IReagentInventoryService reagentInventoryService;
	
	/**
	 * 新增单样品
	 * @param pa
	 * @return
	 */
	public SampleSpecVo addSampleOne(SampleAddPa pa) {
		Map<Integer, String> unitMap = dictService.getUnitMap();
		Map<Integer, String> zoneMap = dictService.getZoneMap();
		//1、保存Kit信息
		Kit kit = MyBeanUtils.copyBean(pa, Kit.class);
		kit.setId(null);
		kit.setClassify(KitEnum.Classify.SAMPLE.getValue());
		kit.setKitType(KitEnum.KitType.ONE.getValue());
		kit = kitService.insert(kit);
		
		//1.1保存Kit附件
		if(!CollectionUtils.isEmpty(pa.getInstructionFileList())) {
			for (FileManage file : pa.getInstructionFileList()) {
				fileManageService.insertBatch(file.getPath(), kit.getId(), OssFileEnum.KitInstructionFile, kit.getLabId(), null);
			}
		}
		if(pa.getTempFileIds()!=null && pa.getTempFileIds().length>0) {
			fileManageService.relevanceBatch(pa.getTempFileIds(), kit.getId(), OssFileEnum.KitInstructionFile, kit.getLabId(), null);
		}
		
		//2、保存试剂信息
		Reagent reagent = MyBeanUtils.copyBean(kit, Reagent.class);
		reagent.setId(null);
		reagent.setKitId(kit.getId());
		reagent = reagentService.insert(reagent);
		
		//3、保存规格信息
		KitSpec kitSpec = MyBeanUtils.copyBean(pa, KitSpec.class);
		kitSpec.setId(null);
		kitSpec.setKitId(kit.getId());
		kitSpec.setReagentId(reagent.getId());
		kitSpec.setKitSize(pa.getSize().multiply(BigDecimal.valueOf(pa.getMultiple())));
		kitSpec = kitSpecService.insert(kitSpec);

		//4、保存属性信息
		List<SampleAttrPa> attrPaList = pa.getSampleAttrList();
		if(!CollectionUtils.isEmpty(attrPaList)) {
			List<SampleAttr> attrList = new ArrayList<SampleAttr>();
			for (SampleAttrPa attr : attrPaList) {
				SampleAttr sampleAttr = new SampleAttr();
				sampleAttr.setLabId(pa.getLabId());
				sampleAttr.setReagentTypeId(pa.getReagentTypeId());
				sampleAttr.setKitId(kit.getId());
				sampleAttr.setReagentId(reagent.getId());
				sampleAttr.setSampleTemplateId(attr.getSampleTemplateId());
				sampleAttr.setUnitName(attr.getUnitName());
				sampleAttr.setAttrName(attr.getAttrName());
				sampleAttr.setAttrValue(attr.getAttrValue());
				sampleAttr.setJsonData(attr.getJsonData());
				attrList.add(sampleAttr);
			}
			sampleAttrService.insertBatch(attrList);
		}
		
		SampleSpecVo vo = new SampleSpecVo();
		vo.setKitId(kit.getId());
		vo.setReagentId(reagent.getId());
		vo.setName(reagent.getName());
		vo.setSize(kitSpec.getSize());
		vo.setUnit(kitSpec.getUnit());
		vo.setMultiple(kitSpec.getMultiple());
		vo.setUnitName(unitMap.get(kitSpec.getUnit()));
		vo.setZone(reagent.getZone());
		vo.setZoneName(zoneMap.get(reagent.getZone()));
		vo.setKitSpecId(kitSpec.getId());
		vo.setReagentTypeId(reagent.getReagentTypeId());
		String specName = kitSpec.getSize().stripTrailingZeros().toPlainString()+unitMap.get(kitSpec.getUnit());
		if(kitSpec.getMultiple()>0) specName += "*"+kitSpec.getMultiple();
		vo.setSpecName(specName);
		esKitSaveService.kitSave(kit.getId());
		return vo;
	}
	
	/**
	 * 新建多样品
	 * @param pa
	 * @return
	 */
	public List<SampleSpecVo> addSampleMore(SampleAddMorePa pa) {
		List<SampleSpecVo> list = new ArrayList<SampleSpecVo>();		
		List<SampleAddPa> sampleList = pa.getSampleAddList();
		Long kitGroup = kitService.getKitGroup();
		for (SampleAddPa sampleAddPa : sampleList) {
			sampleAddPa.setCreatorId(pa.getCreatorId());
			sampleAddPa.setLabId(pa.getLabId());
			sampleAddPa.setKitGroup(kitGroup);
			sampleAddPa.setReagentTypeId(pa.getReagentTypeId());
			SampleSpecVo sampleAddVo = this.addSampleOne(sampleAddPa);
			list.add(sampleAddVo);
		}
		return list;
	}
	
	/**
	 * 样品列表分页
	 * @param pa
	 * @return
	 */
	public PageVo<SampleListVo> sampleList(SampleSearchPa pa,UserInfoVo user){
		PageVo<SampleListVo> pageVo = kitService.sampleList(pa,user.getLabId(),user.getLabMemberId());
		if(pageVo.getContent()!=null && pageVo.getContent().size()>0){
			//获取可用量
			pageVo.getContent().forEach(vo -> {
				if(vo.getReagentTypeId().equals(ServiceConstant.bacteria_reagent_type_id) 
						|| vo.getReagentTypeId().equals(ServiceConstant.cells_reagent_type_id) 
						|| vo.getReagentTypeId().equals(ServiceConstant.viruses_reagent_type_id)){
					vo.setIsStorage(1);
				}
			});
		}
		return pageVo;
	}
	
	/**
	 * 样品信息
	 * @param pa
	 * @return
	 */
	public SampleInfoVo getSampleInfo(Long kitId, Long labMemberId){
		
		Kit kit = kitService.selectById(kitId);
		Assert.isTrue(Classify.SAMPLE.getValue().equals(kit.getClassify() ), ResultEnum.REQUEST_PARAM_ERROR.getMessage());
		
		Map<Integer, String> unitMap = dictService.getUnitMap();
		Map<Integer, String> zoneMap = dictService.getZoneMap();
		Map<Long, String> reagentTypeMap = dictService.getReagentTypeMap(kit.getLabId());
		SampleInfoVo vo = MyBeanUtils.copyBean(kit, SampleInfoVo.class);
		vo.setIsLabExist(1);
		vo.setKitId(kit.getId());
		vo.setReagentTypeName(reagentTypeMap.get(kit.getReagentTypeId()));
		vo.setUnitName(unitMap.get(kit.getUnit()));
		vo.setZoneName(zoneMap.get(kit.getZone()));
		List<FileManage> fileList = fileManageService.selectList(OssFileEnum.KitInstructionFile,kit.getId());
		vo.setFileList(fileList);
		
		//组装规格
		List<KitSpec> specList = kitSpecService.selectSpecGroup(kit.getId());
		KitSpec kitSpec = specList.get(0);
		vo.setKitSpecId(kitSpec.getId());
		vo.setReagentId(kitSpec.getReagentId());
		vo.setSize(kitSpec.getSize());
		vo.setMultiple(kitSpec.getMultiple());
		String specName = kitSpecService.getSpecName(specList,1);
		vo.setSpecName(specName);
		
		//组装属性值
		List<SampleTemplateGroupVo> groupList = sampleTemplateService.getSampleTemplateGroup(kit.getReagentTypeId(), kit.getLabId(),labMemberId);	
		List<SampleAttr> attrList = sampleAttrService.selectList(kitId);
		if(!CollectionUtils.isEmpty(groupList)){
			Map<Long, List<SampleAttr>> attrMapp = attrList.stream().collect(Collectors.groupingBy(SampleAttr::getSampleTemplateId));
			groupList.forEach(groupVo -> {
				List<SampleTemplate> templateList = groupVo.getTemplateList();
				if(!CollectionUtils.isEmpty(templateList)) {
					for (Iterator<SampleTemplate> iterator = templateList.iterator(); iterator.hasNext();) {
						SampleTemplate template = iterator.next();
						List<SampleAttr> list = attrMapp.get(template.getId());
						if(!CollectionUtils.isEmpty(list)) {
							SampleAttr attr = list.get(0);
							if(StringUtils.isNotBlank(attr.getAttrValue()) 
									|| BoolEnum.FALSE.getValue().equals(template.getIsHide())) {
								template.setSampleAttrId(attr.getId());
								template.setAttrValue(attr.getAttrValue());
								template.setIsHide(BoolEnum.FALSE.getValue());
							}
						}
						if(BoolEnum.TRUE.getValue().equals(template.getIsHide())){
							iterator.remove();
						}
					}
				}
			});
			for (Iterator<SampleTemplateGroupVo> iterator = groupList.iterator(); iterator.hasNext();) {
				SampleTemplateGroupVo groupVo = iterator.next();
				if(CollectionUtils.isEmpty(groupVo.getTemplateList()) && !"基础属性".equals(groupVo.getGroupName())) {
					iterator.remove();
				}
			}
		}
		vo.setSampleAttrList(groupList);
		return vo;
	}
	
	/**
	 * 修改试剂
	 * @param pa
	 * @return
	 */
	public void sampleModify(SampleModifyPa pa) {
		List<SampleAttr> attrList = pa.getSampleAttrList();
		if(attrList!=null && attrList.size()>0) {
			Kit kit = new Kit();
			kit.setId(pa.getKitId());
			kit.setItemNo(pa.getItemNo());
			kit.setCompanyId(pa.getCompanyId());
			kit.setCompany(pa.getCompany());
			kit.setRemark(pa.getRemark());
			kitService.updateById(kit);
			if(pa.getTempFileIds()!=null && pa.getTempFileIds().length>0) {
				fileManageService.relevanceBatch(pa.getTempFileIds(), kit.getId(), OssFileEnum.KitInstructionFile, kit.getLabId(), null);
			}
			Reagent reagent = reagentService.selectList(pa.getKitId()).get(0);
			for (SampleAttr sampleAttr : attrList) {
				sampleAttr.setId(null);
				sampleAttr.setLabId(reagent.getLabId());
				sampleAttr.setReagentTypeId(reagent.getReagentTypeId());
				sampleAttr.setKitId(reagent.getKitId());
				sampleAttr.setReagentId(reagent.getId());
			}
			sampleAttrService.deleteByKitId(pa.getKitId());
			sampleAttrService.insertBatch(attrList);
		}
	}
	
	/**
	 * 获取样品规格
	 * @param kitId
	 * @return
	 */
	public SampleSpecVo getSampleSpec(Long kitId) {
		Map<Integer, String> unitMap = dictService.getUnitMap();
		Map<Integer, String> zoneMap = dictService.getZoneMap();
		Reagent reagent = reagentService.selectList(kitId).get(0);
		List<KitSpec> specList = kitSpecService.selectList(kitId, null);
		KitSpec kitSpec = specList.get(0);
		SampleSpecVo vo = new SampleSpecVo();
		vo.setKitId(reagent.getKitId());
		vo.setKitSpecId(kitSpec.getId());
		vo.setReagentId(reagent.getId());
		vo.setName(reagent.getName());
		vo.setSize(kitSpec.getSize());
		vo.setUnit(kitSpec.getUnit());
		vo.setMultiple(kitSpec.getMultiple());
		vo.setZoneName(zoneMap.get(reagent.getZone()));
		vo.setUnitName(unitMap.get(kitSpec.getUnit()));
		vo.setZone(reagent.getZone());
		vo.setReagentTypeId(reagent.getReagentTypeId());
		String specName = kitSpecService.getSpecName(specList, 1);
		vo.setSpecName(specName);
		return vo;
	}
	
	
}
